<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Continent as ContinentModel;
use app\user\model\Merchant as MerchantModel;
use app\user\model\Airport as AirportModel;
use app\user\model\Category as CategoryModel;

/**
 * 商户控制器
 * @package app\user\admin
 */
class Merchant extends Admin
{
    /**
     * 商户列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = MerchantModel::where($this->getMap())
            ->order($this->getOrder('id DESC'))
            ->paginate();
        if($data_list->items()){
            foreach ($data_list->items() as &$val){
//                $phone_code=ContinentModel::where(['id'=>$val['countr y'],'type'=>'country'])->value('phone_code');
                $val['country']=ContinentModel::where(['id'=>$val['country'],'type'=>'country'])->value('name');
                $airportInfo=AirportModel::where('id',$val['airport'])->field(['iata','city'])->find()->toArray();
                $val['city']=ContinentModel::where(['id'=>$airportInfo['city'],'type'=>'city'])->value('name');
//                $val['account']='+'.$phone_code.' '.$val['account'];
                $val['iata']=$airportInfo['iata'];
            }
        }

        $airports=AirportModel::column(['id','name']);
        $btn_access = [
            'title' => 'view',
            'icon'  => 'fa fa-fw fa-search',
            'href'  => url('view', ['id' => '__id__'])
        ];
        return ZBuilder::make('table')
            ->setTableName('merchant')
            ->addColumns([
                ['id', 'ID'],
                ['account', 'Account'],
                ['name', 'Merchant'],
                ['iata', 'IATA'],
                ['terminal', 'Terminal'],
                ['email', 'Email'],
                ['country', 'Country'],
                ['city', 'City'],
                ['status', 'Status','status','',[1=>'normal',0=>'lock:warning',-1=>'cancel:danger']],
                ['right_button', 'Operation', 'btn'],
            ])
            ->addRightButton('custom', $btn_access)
            ->addTopButton('enable',['table'=>'merchant','title'=>'Unlock','icon'  => 'fa fa-fw fa-unlock','data-title'=>'Unlocked merchants will regain the right to publish content and edit information. Do you want to continue?'])
            ->addTopButton('disable',['table'=>'merchant','title'=>'Lock','icon'  => 'fa fa-fw fa-lock', 'data-title' =>'Locked merchants will temporarily lose the right to publish content and edit information, do you want to continue?'])
            ->setRowList($data_list)
            ->setSearchArea([
                ['text', 'name', 'Merchant','like'],
                ['text', 'account', 'Account','like'],
                ['select', 'airport', 'Airport', '', '', $airports],
                ['select', 'status', 'Status', '', '', [1=>'normal',0=>'lock',-1=>'cancel']]
            ])
            ->setColumnWidth([
                'id'=>30,
                'iata'=>60,
                'country'=>60,
                'city'=>60,
                'status'=>60,
                'terminal'=>70,
                'right_button'=>50
            ])
            ->fetch();
    }

    public function view($id = 0)
    {

        if ($id === 0) $this->error('missing parameter');
        $js = <<<EOF
            <script type="text/javascript">
                $('#Lock').click(function(){
                    var id=$(this).attr('data-id');
                    $.ajax({
                                url : '/admin.php/user/merchant/lock',
                                type : 'POST',
                                data : { id : id},
                                dataType: 'json',
                                success : function(res) {
                                    if (res.code==200) {
                                        Dolphin.notify('update success', 'success');
                                        setTimeout(function(){
                                            location.reload();

                                        }, 2000);
                                    } else {
                                        Dolphin.notify(res.msg, 'danger');
                                    }
                                }
                            });
                });
                
                $('#Unlock').click(function(){
                    var id=$(this).attr('data-id');
                    $.ajax({
                                url : '/admin.php/user/merchant/unlock',
                                type : 'POST',
                                data : { id : id},
                                dataType: 'json',
                                success : function(res) {
                                    if (res.code==200) {
                                        Dolphin.notify('update success', 'success');
                                        setTimeout(function(){
                                            location.reload();
                                        }, 2000);
                                    } else {
                                        Dolphin.notify(res.msg, 'danger');
                                    }
                                }
                            });
                });
            </script>
EOF;
        // 获取数据
        $info = MerchantModel::get($id);
        $lock_btn = [
            'title' => 'Lock',
            'data-id'=>$info['id']
            //'href' => url('lock',['id'=>$info['id']]) // 此属性仅用于a标签按钮，button按钮不产生作用
        ];
        $unlock_btn = [
            'title' => 'Unlock',
            'data-id'=>$info['id']
            //'href' => url('unlock',['id'=>$info['id']]) // 此属性仅用于a标签按钮，button按钮不产生作用
        ];
        $address_btn=[
            'title'=>'Address',
            'icon'=>'fa fa-fw fa-location-arrow',
            'target' => '_blank',
            'href' => $info['address_link']
        ];
        $country_name=ContinentModel::where(['id'=>$info['country'],'type'=>'country'])->value('name');
        $city_id=AirportModel::where(['id'=>$info['airport']])->value('city');
        $city_name=ContinentModel::where(['id'=>$city_id,'type'=>'city'])->value('name');
        $airport_name=AirportModel::where(['id'=>$info['airport']])->value('name');
        $info['location_name']=$city_name.','.$country_name;
        $info['airport_name']=$airport_name;
        //$info['phone']=$info['phone']?implode('/',json_decode($info['phone'],true)):'';
        $info['open_time']=$info['start_time'].'-'.$info['end_time'];
        $info['category']=CategoryModel::where(['id'=>$info['category']])->value('name');
        $subCategory=$info['sub_category']?CategoryModel::getSubCategory($info['sub_category']):'';
        $info['category']=$info['category']?$info['category'].'-'.implode(',',$subCategory):'';
        $images='';
        if($info['images']){
            $images=json_decode($info['images'],true);
            foreach ($images as &$val){
                $val='/'.$val;
            }
            $images=implode(',',$images);
        }
        $info['images']=$images;
        $info['header_image']=$info['header_image']?'/'.$info['header_image']:'';
        $info['avatar']=$info['avatar']?'/'.$info['avatar']:'/uploads/default/merchant_avatar.png';
        // 使用ZBuilder快速创建表单
        $form=ZBuilder::make('form')
            ->addFormItems([
                ['text:3', 'name', 'Name','','','','readonly'],
                ['select:3', 'status', 'Status','',[1=>'normal',0=>'lock',-1=>'cancel'],''],
                ['text:3','account','Account','','','','readonly'],
                ]);
        if($info['status']==1){
            $form=$form->addFormItems([
                ['button:1','Lock',$lock_btn],
            ]);
        }elseif($info['status']==0){
            $form=$form->addFormItems([
                ['button:1','Unlock',$unlock_btn],
            ]);
        }else{
            $form=$form->addFormItems([
                ['button:1','Lock',$lock_btn],
                ['button:1','Unlock',$unlock_btn],
            ]);
        }
        $form=$form->addFormItems([
                ['text:3','email','Email','','','','readonly'],
                ['text:3','location_name','City,Couuntry','','','','readonly'],
                ['text:3','airport_name','Airport','','','','readonly'],
                ['text:3','terminal','Terminal','','','','readonly'],
                ['text:3','phone_number','Phone','','','','readonly'],
                ['text:3','address','Address','','','','readonly'],
            ]);
        if($info['address_link']){
            if(!strstr($info['address_link'],'http')){
                $address_btn['href']='http://'.$info['address_link'];
            }
            $form=$form->addFormItems([
                ['button:4','Link',$address_btn,'a'],
            ]);
        }

        $form= $form->addFormItems([
            ['hidden:3','open_time','Hours','','','','readonly'],
            ['text:3','open_time','Hours','','','','readonly'],
//            ['text:3','address','Address','','','','readonly'],
            ['text:3','category','Category','','','','readonly'],
            ['textarea','profile','Profile','','','','readonly'],
            ['gallery','images','Images','', '', '', '', '',['size'=>'100,100']],
            ['gallery','avatar','Avatar'],
            ['gallery','header_image','header_image']
        ]);


        return $form->setFormData($info)->hideBtn('submit')->setExtraJs($js)
            ->fetch();
    }

    public function lock(){
        $id=$_POST['id'];
        if(empty($id) || !is_numeric($id)){
            echo json_encode(['code'=>500,'msg'=>'ID is not a number']);
            die;
        }
        MerchantModel::where('id',$id)->update(['status'=>0]);
        echo json_encode(['code'=>200]);
    }

    public function unlock(){
        $id=$_POST['id'];
        if(empty($id) || !is_numeric($id)){
            echo json_encode(['code'=>500,'msg'=>'ID is not a number']);
            die;
        }
        MerchantModel::where('id',$id)->update(['status'=>1]);
        echo json_encode(['code'=>200]);
    }
}
